package MyGui;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

import DistSys.Sys;
import DistSys.Zone;
import Element.AbsElem;

public class SelectZoneDlg extends MyDlgFrame implements ActionListener{
    private ZoneComboBox comboZone;
    private JButton btnSelect, btnAddToSelection;

    public SelectZoneDlg(MainFrame parent, String title) {
        super(parent, title);

        comboZone = new ZoneComboBox(false);
        JLabel lblZone = new JLabel("Zone:");
        lblZone.setLabelFor(comboZone);
        lblZone.setDisplayedMnemonic('Z');
        btnSelect = new JButton("Select");
        btnAddToSelection = new JButton("Add to Selection");

        Container pane = this.getContentPane();
        pane.setLayout(gridBagLayout);
        GridBagConstraints c = new GridBagConstraints();

        c.insets = new Insets(GAP, GAP, 0, 0);
        c.fill = GridBagConstraints.HORIZONTAL;

        c.gridy = 0;
        c.gridx = 0; pane.add(lblZone, c);
        c.weightx = 1; c.insets.right = GAP;
        c.gridx = 1; pane.add(comboZone, c);

        c.gridx = 0; c.gridwidth = 2;
        c.gridy = 1; pane.add(btnSelect, c);
        c.weighty = 1; c.anchor = GridBagConstraints.NORTH;
        c.insets.bottom = GAP;
        c.gridy = 2; pane.add(btnAddToSelection, c);

        btnSelect.addActionListener(this);
        btnAddToSelection.addActionListener(this);

        this.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
        this.setSize(220,130);
    }

    public void actionPerformed(ActionEvent evt){
        double dZone;
        try {
            dZone = comboZone.getSelectedZone();
        } catch(ZoneComboBox.ZoneException e) {
            JOptionPane.showMessageDialog(getParent(),
                "'" + e.getMessage() + "' is not a valid zone.");
            return;
        }

        if (evt.getSource() == btnSelect) {
            // must to clear first
            Sys.clearSelectionAndFocus();
        }

        for (int i = 0; i < Sys.elemList.size(); i++) {
            AbsElem elem = (AbsElem) Sys.elemList.elementAt(i);
            if (Zone.getZoneFits(dZone, elem)) {
                Sys.addElemToSelection(elem);
            }
        }
        mainFrame.mainPanel.needRedraw = true;
        mainFrame.mainPanel.repaint();
    }
}